import axios from 'axios';
import { notification, Modal } from 'antd';
import { getToken } from '@/utils/auth';
import { getDvaApp } from 'umi';
const { NODE_ENV } = process.env;

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: NODE_ENV == 'development' ? '/dev-api' : '/prod-api',
  // 超时
  timeout: 10000,
});
// request拦截器
service.interceptors.request.use(
  (config) => {
    if (getToken()) {
      config.headers['Authorization'] = 'Bearer ' + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config;
  },
  (error) => {
    console.log(error);
    Promise.reject(error);
  },
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    const code = res.data.code;
    if (code === 401) {
      getDvaApp()._store.dispatch({
        type: 'login/logout',
      });
    } else if (code !== 200) {
      notification.error({
        message: `请求错误`,
        description: res.data.msg,
      });
      return Promise.reject(res.data);
    } else {
      return res.data;
    }
  },
  (error) => {
    // console.log('err ');
    // console.log(error.message)
    notification.error({
      message: `请求错误`,
      description: error.message,
    });
    return Promise.reject(error);
  },
);

export default service;
